import moment from "moment-timezone";
import i18n from "@/i18n";
import { useStore } from "@/stores";
import { GroupInfo, FriendInfoSelect } from "@/api/ImApi";
export function goTo(url: string, title: string = "") {
  uni.navigateTo({
    url,
    success: () => {
      if (title) {
        setTimeout(() => {
          uni.showToast({
            title,
            icon: "none",
          });
        });
      }
    },
  });
}
export function goToTab(url: string) {
  uni.switchTab({
    url: url,
  });
}
export function goBack(delta: number, title: string = "") {
  const canNavBack = getCurrentPages();
  if (canNavBack && canNavBack.length > 1) {
    uni.navigateBack({
      delta,
      success: () => {
        if (title) {
          setTimeout(() => {
            uni.showToast({
              title,
              icon: "none",
            });
          }, 100);
        }
      },
    });
  } else {
    uni.reLaunch({
      url: "/pages/index/index",
    });
  }
}
export function goReLaunch(url: string, title: string = "") {
  uni.reLaunch({
    url,
    success: () => {
      if (title) {
        setTimeout(() => {
          uni.showToast({
            title,
            icon: "none",
          });
        }, 100);
      }
    },
  });
}
export function goRedirectTo(url: string, title: string = "") {
  uni.redirectTo({
    url: url,
    success: () => {
      if (title) {
        setTimeout(() => {
          uni.showToast({
            title,
            icon: "none",
          });
        }, 100);
      }
    },
  });
}
export function copyText(data: string) {
  uni.setClipboardData({
    data,
    showToast: false,
    success: () => {
      uni.showToast({
        title: "复制成功",
        icon: "none",
      });
    },
  });
}
// 时间进制
export function formattingTime(time: string | number, type: number): string {
  // 从 localStorage 中获取 UTC 偏移值，默认值为 0
  const utcOffsetMinutes = Number(uni.getStorageSync("utcOffsetMinutes") || 0);

  // 通用的格式化函数
  const formatTime = (time: moment.Moment, format: string): string =>
    time.utc().utcOffset(utcOffsetMinutes).format(format);

  // 类型为 1，返回 "YYYY/MM/DD"
  if (type === 1) {
    return formatTime(moment(time), "YYYY/MM/DD");
  }

  // 类型为 2，聊天时间格式
  if (type === 2) {
    const currentDate = moment(); // 当前时间
    const messageDate = moment(time).utc().utcOffset(utcOffsetMinutes); // 消息时间
    const diffDays = currentDate.diff(messageDate, "days"); // 当前日期与消息日期的天数差

    const hours = messageDate.hours(); // 小时
    const minutes = messageDate.minutes(); // 分钟（补零处理）
    const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;
    // 今天的消息
    if (diffDays < 1) {
      return `${hours}:${formattedMinutes}`; // 返回时和分
    }

    // 昨天的消息
    if (diffDays === 1) {
      return `昨天${hours}:${formattedMinutes}`;
    }

    // 最近一周的消息
    if (diffDays <= 7) {
      return `${diffDays}天前`;
    }

    // 更早的消息
    return formatTime(messageDate, "YYYY/MM/DD");
  }

  // 默认格式化返回 "YYYY/MM/DD HH:mm:ss"
  return formatTime(moment(time), "YYYY/MM/DD HH:mm:ss");
}

// 显示时间的函数
export function shouldShowTime(index: number, messagesList: any[]): boolean {
  if (index === 0) return true; // 第一个消息显示时间

  // 获取当前消息和下一条消息的索引
  const currentMessage = messagesList[index];
  const nextMessage = messagesList[index + 1]; // 倒序时的上一条消息

  // 确保当前消息和下一条消息存在，并有 Time 属性
  if (!currentMessage?.Time || !nextMessage?.Time) {
    return false; // 如果任意一条消息没有时间，直接返回 false
  }

  // 计算时间差（毫秒）并转换为分钟
  const timeDifference = (currentMessage.Time - nextMessage.Time) / (1000 * 60);

  return timeDifference >= 5; // 如果相差 5 分钟以上，返回 true
}

// 深copy
export function deepClone(obj: any): any {
  if (obj === null || typeof obj !== "object") return obj;
  if (Array.isArray(obj)) return obj.map((item) => deepClone(item));
  const newObj: any = {};
  Object.keys(obj).forEach((key) => {
    newObj[key] = deepClone(obj[key]);
  });
  return newObj;
}

// 获取图片宽高，添加重试机制
export async function getImageDimensions(
  url: string,
  retryCount = 0
): Promise<{ width: number; height: number }> {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: url,
      success: async (res) => {
        let { width, height } = await getmaxSize(res);
        resolve({
          width: Math.round(width),
          height: Math.round(height),
        });
      },
      fail: async () => {
        if (retryCount < 100) {
          // 如果重试次数小于 10 次，则等待 1 秒后重试
          console.log(`第 ${retryCount + 1} 次重试获取图片尺寸: ${url}`);
          await new Promise((resolve) => setTimeout(resolve, 1000)); // 等待 1 秒
          resolve(await getImageDimensions(url, retryCount + 1)); // 递归调用，增加重试次数
        } else {
          // 如果重试 10 次仍然失败，返回默认的宽高
          resolve({
            width: 150,
            height: 150,
          });
        }
      },
    });
  });
}
// 控制最大尺寸
export function getmaxSize(obj: any): any {
  const maxWidth = 300;
  const maxHeight = 300;
  let width = obj.width;
  let height = obj.height;
  // 先根据宽度进行缩放
  if (obj.width > maxWidth) {
    const scale = maxWidth / width;
    width = maxWidth;
    height = height * scale;
  }

  // 再根据高度进行缩放
  if (height > maxHeight) {
    const scale = maxHeight / height;
    height = maxHeight;
    width = width * scale;
  }
  return { width, height };
}

// 转换视频时长
export function getVideoDuration(Time: any): any {
  if (!Time) {
    return;
  }
  return (
    moment.duration(Time, "seconds").minutes() +
    ":" +
    moment.duration(Time, "seconds").seconds().toString().padStart(2, "0")
  );
}

// 判断类型
export function typeCopywriting(item: any): string {
  let text = "";
  let myUserInfo = uni.getStorageSync("userInfo");
  if (item.Grade == 2) {
    return item.Content?.Text;
  }
  switch (item.Cmd) {
    case 2:
      text = "[图片]";
      break;
    case 3:
      text = "[视频]";
      break;
    case 4:
      text = "[语音] " + item.Content?.Time + '"';
      break;
    case 5:
      text = "[文件] " + item.Content?.FileName;
      break;
    case 6:
      text = "[红包]";
      break;
    default:
      text = item.Content?.Text || "";
  }

  return item.Type == 2 && myUserInfo.user_id != item.Sender.user_id
    ? (item.Sender.nick_name ? item.Sender.nick_name + "：" : "") + text
    : "" + text;
}
// 获取文件扩展显示图片
export function getImageSrc(fileName: string): string {
  console.log("fileName", fileName);

  // 获取文件扩展名
  const fileType = fileName?.split(".").pop()?.toLowerCase() || "other";

  // 允许的文件扩展名列表
  const allowedTypes = [
    "txt",
    "pdf",
    "ppt",
    "doc",
    "docx",
    "xls",
    "xlsx",
    "zip",
    "7z",
    "rar",
  ];

  const validFileType = allowedTypes.includes(fileType) ? fileType : "other";

  return `/static/image/document/${validFileType}.png`;
}

/**
 * 将字节转换为适当的单位（KB, MB, GB, etc.）
 * @param bytes 字节数
 * @param decimals 保留的小数位数，默认为 1
 * @returns 转换后的字符串
 */
export const formatBytes = (bytes: number, decimals: number = 1): string => {
  if (bytes === 0) return "0 Bytes"; // 处理 0 字节的情况

  const k = 1024; // 一千零二十四字节为一 KB
  const dm = decimals < 0 ? 0 : decimals; // 保证小数位不小于 0
  const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; // 可扩展单位

  // 计算单位索引
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  // 返回格式化后的结果，保留指定小数位
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + sizes[i];
};
// 下载文件
export function handleDownload(url: string): void {
  /*#ifdef APP-PLUS*/
  openExternalBrowser(url);
  /*#endif*/
  /*#ifdef H5*/
  window.location.href = url;
  /*#endif*/
}

// 打开外部浏览器
const openExternalBrowser = function (url: string) {
  // 判断平台
  const platform = uni.getSystemInfoSync().platform;
  if (platform === "android") {
    // 在Android平台上使用外部浏览器
    plus.runtime.openURL(url, function (error: any) {
      console.error("打开外部浏览器出错: " + error.message);
    });
  } else if (platform === "ios") {
    // 在iOS平台上使用外部浏览器
    plus.runtime.openWeb(url);
  } else {
    // 其他平台可能不支持直接打开外部浏览器，可以尝试使用 uni.navigateTo
    uni.navigateTo({
      url: "/pages/chat/filePreview?attachmentUrl=" + encodeURIComponent(url),
    });
  }
};

// 存入chatList数据
export async function setChatList(obj: any, id: string | number) {
  const store = useStore();
  let chatList = await store.db.loadData("chatList", {
    id,
  });
  let info: any = {};
  if (chatList.length) {
    info = chatList[0];
  } else {
    if (obj.Type == 1) {
      info = await FriendInfoSelect({ user_id: id });
    }
    if (obj.Type == 2) {
      info = await GroupInfo({ group_id: id });
    }
  }
  let arr = [
    {
      ...info,
      ...obj,
    },
  ];
  console.warn("覆盖并且添加", arr);
  console.log(arr);
  await store.db.saveData("chatList", arr);
}

// 判断是否超过24小时
export const isExpiredFn = async (time: number) => {
  const utcOffsetMinutes = Number(uni.getStorageSync("utcOffsetMinutes") || 0);

  // 获取当前时间并应用时区偏移
  const momentTime = moment()
    .utc()
    .utcOffset(utcOffsetMinutes)
    .format("YYYY/MM/DD HH:mm:ss");

  // 将格式化后的时间转换为时间戳
  const currentTime = moment(momentTime, "YYYY/MM/DD HH:mm:ss").valueOf();

  // 比较是否超过24小时
  return currentTime - time > 1000 * 60 * 60 * 24;
};
